//
//  M3U8VideoDownLoader.m
//  m3u8Player
//
//  Created by 缴天朔 on 2021/8/18.
//

#import "M3U8VideoDownLoader.h"
#import "M3U8SegmentModel.h"
#import "SegmentDownloader.h"

@interface M3U8VideoDownLoader() <SegmentDownloaderDelegate>{
    NSInteger totalCount;
}

@property (assign, nonatomic) NSInteger index;//记录一共多少TS文件

@property (assign, nonatomic) NSInteger sIndex;//当前拼接链接的索引

@end

@implementation M3U8VideoDownLoader

-(instancetype)init{
    self = [super init];
    if(self){
        self.index = 0;
        self.sIndex = 0;
        self.downloadedNum = 0;
    }
    return self;
}

#pragma mark - 下载TS数据
-(void)startDownLoadVideo{
    
    //首先检查是否存在路径
    [self checkDirectoryIsCreateM3U8:NO];
    
    totalCount = self.playlist.segmentArray.count;
    

    //初始化下载器，后面通过回调打包新的下载器。
    for(int i = 0; i < 3; i ++){
        if (self.index >= totalCount) {
            break;
        }
        M3U8SegmentModel *obj = [self.playlist.segmentArray objectAtIndex:self.index];
        NSString *fileName = [NSString stringWithFormat:@"movie%ld.ts",self.index];
        
        NSURL *url = [[NSURL alloc] initWithString:obj.locationUrl];
        //打包下载器
        SegmentDownloader *sgDownloader = [[SegmentDownloader alloc] initWithUrl:url andFilePath:self.playlist.uuid andFileName:fileName withDuration:obj.duration withIndex:self.index withTotalCount:totalCount];
        sgDownloader.delegate = self;
        
        
        //更新playlist
        obj.index = self.index;
        obj.locationUrl = fileName;
        
        self.index ++;
        
        [sgDownloader start];
    }
    
    
    //打包下载key
    if (self.keyUrl != nil) {
        SegmentDownloader *keyDownloader = [[SegmentDownloader alloc] initWithUrl:self.keyUrl andFilePath:nil andFileName:@"key.key" withDuration:0 withIndex:0 withTotalCount:0];
        [keyDownloader start];
    }
}

#pragma mark - 打包下载器并开始下载
-(void)newSegmentDownloader{
    M3U8SegmentModel *obj = [self.playlist.segmentArray objectAtIndex:self.index];
    NSString *fileName = [NSString stringWithFormat:@"movie%ld.ts",self.index];
    
    NSURL *url = [[NSURL alloc] initWithString:obj.locationUrl];
    //打包下载器
    SegmentDownloader *sgDownloader = [[SegmentDownloader alloc] initWithUrl:url andFilePath:self.playlist.uuid andFileName:fileName withDuration:obj.duration withIndex:self.index withTotalCount:totalCount];
    sgDownloader.delegate = self;

    //更新playlist
    obj.index = self.index;
    obj.locationUrl = fileName;
    self.index ++;
    [sgDownloader start];
    
}

#pragma mark - 检查路径
-(void)checkDirectoryIsCreateM3U8:(BOOL)isC{
    //创建缓存路径
    NSString *saveTo = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    NSFileManager *fm = [[NSFileManager alloc] init];
    
    //路径不存在创建一个
    BOOL isD = [fm fileExistsAtPath:saveTo];
    if (isD) {
        //存在
    }else{
        //不存在
        BOOL isS = [fm createDirectoryAtPath:saveTo withIntermediateDirectories:YES attributes:nil error:nil];
        if (isS) {
            NSLog(@"路径不存在创建成功");
        }else{
            NSLog(@"路径不存在创建失败");
        }
    }
}


#pragma mark - 数据下载失败
- (void)segmentDownloadFailed:(nonnull SegmentDownloader *)downloader {
    [self.delegate videoDownLoaderFailed:self];
    [downloader start];
}

#pragma mark - 数据下载成功
- (void)segmentDownloadFinished:(nonnull SegmentDownloader *)downloader {
    //记录成功下载文件个数
    self.downloadedNum ++;
    
    //加入新的下载器
    if(self.index < totalCount){
        [self newSegmentDownloader];
    }
    
    if (self.downloadedNum == totalCount ) {
        //每次下载完成后都要创建M3U8文件
//        [self createLocalM3U8File];
        //证明所有的TS已经下载完成
//        [self.delegate videoDownLoaderFinished:self];
        NSLog(@"所有文件已经成功下载");
        
    }
}



#pragma mark - 创建M3U8文件
-(void)createLocalM3U8File{
    NSLog(@"开始创建m3u8");
    [self checkDirectoryIsCreateM3U8:YES];
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"movie.m3u8"];
    
    //拼接M3U8链接头部内容
    NSString *header = [NSString stringWithFormat:@"#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:5\n#EXT-X-MEDIA-SEQUENCE:0\n#EXT-X-PLAYLIST-TYPE:EVENT\n"];
    //填充M3U8数据
    __block NSString *tsStr = [[NSString alloc] init];
    [self.playlist.segmentArray enumerateObjectsUsingBlock:^(M3U8SegmentModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *fileName = [NSString stringWithFormat:@"http://127.0.0.1:9479/movie%ld.ts",self.sIndex];
        //http://127.0.0.1:9479/
        //文件时长
        NSString *length = [NSString stringWithFormat:@"#EXTINF:%@,\n",obj.duration];
        
        //拼接M3u8
        tsStr = [tsStr stringByAppendingString:[NSString stringWithFormat:@"%@%@\n",length,fileName]];
        self.sIndex ++;
    }];
    
    //m3u8头部和中间拼接，到此我们完成新的M3U8链接拼接
    header = [header stringByAppendingString:tsStr];
    
    header = [header stringByAppendingString:@"#EXT-X-ENDLIST"];
    
    //拼接完成，存储到本地
    NSMutableData *writer = [[NSMutableData alloc] init];
    NSFileManager *fm = [[NSFileManager alloc] init];
    
    //判断m3u8是否存在，已经存在就不再重新创建
    if ([fm fileExistsAtPath:path isDirectory:nil]) {
        //存在这个链接
        NSLog(@"存在这个链接");
    }else{
        //不存在这个链接
        NSString *saveTo = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        BOOL isS = [fm createDirectoryAtPath:saveTo withIntermediateDirectories:YES attributes:nil error:nil];
        if (isS) {
            //成功
            NSLog(@"M3U8数据保存成功");
        }else{
            //失败
            NSLog(@"M3U8数据保存失败");
        }
    }
        [writer appendData:[header dataUsingEncoding:NSUTF8StringEncoding]];
        BOOL bSucc = [writer writeToFile:path atomically:YES];
        if (bSucc) {
            //成功
            NSLog(@"M3U8数据保存成功");
        }else{
            //失败
            NSLog(@"M3U8数据保存失败");
        }
}

#pragma mark - 删除缓存文件
-(void)deleteCache{
    //获取缓存路径
    NSString *saveTo = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSFileManager *fm = [[NSFileManager alloc] init];
    
    //路径不存在就创建一个
    BOOL isD = [fm fileExistsAtPath:saveTo];
    if (isD) {
        //存在
        NSArray *deleteArray = [fm subpathsAtPath:saveTo];
        //清空当前的M3U8文件
        [deleteArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            BOOL isS = [fm removeItemAtPath:[saveTo stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", obj]] error:nil];
            if (isS) {
                NSLog(@"多余路径存在清空成功%@",obj);
            }else{
                NSLog(@"多余路径存在清空失败%@",obj);
            }
        }];
        
    }
}

@end
